import produce from 'immer';
import { createAction } from '../utils';
import dataConfig from '../configShow/dataConfig';
import * as layerDataService from '../services/layerData';

export default {
  namespace: 'globalShow',
  state: {
    //全局
    logged: false,
    currentUser: { id: 0 },
    dataConfig, //数据配置文件，用于初始化专题数据控件，点击时，dataConfig中的项selected属性会变化
    //--------数据选中----------
    selectedDataTime: '', //选中的数据展示层级，同时用于渲染地图图层和表格数据
    selectedDataTimeSeries: [],
    selectedDataId: '', //
    selectedDataTitle: '', //
    selectedDataType: '',// json or service
    selectedDataConfig: {},
    selectedData: [], //选中的数据
    selectedAllData: [], //选中类型所有数据
    selectedDataFetching: false,
    selectedDataFetchingByTime: false, //时间变化数据获取状态 区别于 类别 和 level
    //---------20190308-------------
    mapZoomLevel: '630',
    selectedDataLevel: '640100', //选中的数据展示层级，用于初始化专题数据控件,同时用于渲染地图图层和表格数据
    currentRendererItem: {},
    currentCamera: {},
    selectedDataTypeList: [],
  },
  reducers: {
    //=================================
    updateState(state, { payload }) {
      return { ...state, ...payload };
    },
    saveMapZoomLevel(state, { payload }) {
      produce(state, draft => {
        draft.mapZoomLevel = payload;
      });
    },
    saveSceneCamera(state, { payload }) {
      produce(state, draft => {
        draft.currentCamera = payload;
      });
    }


  },
  effects: {
    //当选中数据的级别、类型、时间发生变化时，触发重新获取数据的操作
    *setSelectedDataLevel(
      {
        payload: { dataLevel },
      },
      { select, put, call }
    ) {
      const { selectedDataLevel } = select(state => state.globalShow);
      if (dataLevel !== selectedDataLevel) {
        yield put({
          type: 'updateState',
          payload: { selectedDataLevel: dataLevel, selectedDataFetching: true },
        });
        yield put({ type: 'updateSelectedData' });
      }
    },
    *setSelectedDataTime(
      {
        payload: { dataTime },
      },
      { select, put, call }
    ) {
      const { selectedDataTime } = select(state => state.globalShow);
      if (dataTime !== selectedDataTime) {
        yield put({
          type: 'updateState',
          payload: { selectedDataTime: dataTime, selectedDataFetchingByTime: true },
        });
        yield put({ type: 'updateSelectedData' });
      }
    },
    *changeSelectedData(
      {
        payload: { selectedItem },
      },
      { select, put }
    ) {
      //修改DataConfig，控制前端控件的选择状态
      const { dataConfig } = yield select(state => state.globalShow);
      let selectedDataId = '',
        selectedDataTitle = '',
        selectedDataType = '',
        selectedDataTime = '',
        selectedDataTimeSeries = [];
      const newDataConfig = produce(dataConfig, draft => {
        draft.map(item => {
          item.children.forEach(l => {
            if (l.id === selectedItem.id) {
              l.selected = true;
              selectedDataId = l.id;
              selectedDataTitle = l.title;
              selectedDataType = l.dataType;
              if (l.hasTimeLine) {
                selectedDataTime = l.initTime;
                selectedDataTimeSeries = [...l.timeSeries];
              }
            } else {
              l.selected = false;
            }
          });
        });
      });
      yield put(
        createAction('updateState')({
          dataConfig: newDataConfig,
          selectedDataId,
          selectedDataTitle,
          selectedDataType,
          selectedDataTime,
          selectedDataTimeSeries,
          selectedDataFetching: true,
        })
      );
      let currentRendererItem = {};
      // currentRendererItem = Object.assign({}, { selectedItem });
      currentRendererItem = selectedItem;
      yield put(createAction('updateState')({ currentRendererItem }));
      if (selectedItem.dataType === 'json') {
        yield put({ type: 'updateSelectedData' });
      } else if (selectedItem.dataType === 'service') {
        yield put({ type: 'updateSelectedData' });
      }
    },
    *updateSelectedData(_, { select, put, call }) {
      const {
        selectedDataId,
        selectedDataType,
        selectedDataLevel,
        selectedDataTime,
      } = yield select(state => state.globalShow);
      //根据当前数据选择情况获取数据
      //1.年鉴数据返回具体的数据值
      //2.服务数据直接返回对应的服务
      switch (selectedDataType) {
        case 'json':
          var { status, data } = yield call(layerDataService.fetch, {
            dataId: selectedDataId,
            dataLevel: selectedDataLevel,
            dataTime: selectedDataTime});
          if (status) {
            console.log('select data =>', data);
            yield put(createAction('updateState')({ selectedData: data.content }));
          }
          // 获取全部数据
          var { status, data } = yield call(layerDataService.fetch, {
            dataId: selectedDataId,
            dataLevel: null,
            dataTime: null,
          });
          if (status) {
            console.log('select all data =>', data);
            yield put(createAction('updateState')({ selectedAllData: data.content }));
            // 查出全部数据后再 开始渲染
            yield put({
              type: 'updateState',
              payload: { selectedDataFetching: false, selectedDataFetchingByTime: false },
            });
          }
          break;
        case 'service':
          console.log('select data =>', null);
          yield put(createAction('updateState')({ selectedData: null }));
          yield put({
            type: 'updateState',
            payload: { selectedDataFetching: false, selectedDataFetchingByTime: false },
          });
          break;
        case '':
          console.log('select data =>', null);
          yield put(createAction('updateState')({ selectedData: null }));
          yield put({
            type: 'updateState',
            payload: { selectedDataFetching: false, selectedDataFetchingByTime: false },
          });
          break;
      }
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (!pathname.startsWith('/login')) {
          dispatch({
            type: 'userHook',
          });
        }
      });
    },
  },
};
